using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CodRevit.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CodRevit.Services
{
    public class CozeApiService : ICozeApiService
    {
        private readonly HttpClient _httpClient;
        private readonly CozeApiSettings _settings;

        public CozeApiService(CozeApiSettings settings)
        {
            _settings = settings;
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_settings.ApiKey}");
        }

        public async Task<ChatMessage> SendMessageAsync(string message)
        {
            try
            {
                var response = await GetResponseAsync(message);
                return new ChatMessage { Role = "assistant", Content = response };
            }
            catch (Exception ex)
            {
                return new ChatMessage { Role = "assistant", Content = $"抱歉，发生错误：{ex.Message}" };
            }
        }

        private async Task<string> GetResponseAsync(string userMessage)
        {
            try
            {
                var request = new
                {
                    bot_id = _settings.BotId,
                    user_id = "123456789",
                    stream = true,
                    auto_save_history = true,
                    additional_messages = new[]
                    {
                        new
                        {
                            role = "user",
                            content = userMessage,
                            content_type = "text"
                        }
                    }
                };

                var content = new StringContent(
                    JsonConvert.SerializeObject(request),
                    Encoding.UTF8,
                    "application/json"
                );

                var response = await _httpClient.PostAsync(_settings.ApiUrl, content);
                response.EnsureSuccessStatusCode();

                using (var stream = await response.Content.ReadAsStreamAsync())
                using (var reader = new StreamReader(stream))
                {
                    string currentEvent = null;
                    string currentData = null;
                    string answer = null;
                    string line;

                    while ((line = await reader.ReadLineAsync()) != null)
                    {
                        if (string.IsNullOrEmpty(line.Trim()))
                        {
                            if (!string.IsNullOrEmpty(currentEvent) && !string.IsNullOrEmpty(currentData))
                            {
                                try
                                {
                                    if (currentEvent == "conversation.message.completed")
                                    {
                                        var message = JsonConvert.DeserializeObject<JObject>(currentData);
                                        if (message["type"]?.ToString() == "answer")
                                        {
                                            answer = message["content"]?.ToString();
                                        }
                                    }
                                    else if (currentEvent == "done")
                                    {
                                        break;
                                    }
                                }
                                catch (JsonException ex)
                                {
                                    Console.WriteLine($"JSON解析错误: {ex.Message}");
                                }
                            }
                            currentEvent = null;
                            currentData = null;
                            continue;
                        }

                        if (line.StartsWith("event:"))
                        {
                            currentEvent = line.Substring(6).Trim();
                        }
                        else if (line.StartsWith("data:"))
                        {
                            currentData = line.Substring(5).Trim();
                        }
                    }

                    return answer ?? "抱歉，我没有收到有效的回复。";
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"API请求失败: {ex.Message}");
            }
        }
    }
}